多重继承,指的是一个类别可以同时从多于一个父类继承行为与特征的功能,Python
是支持多重继承的:
class Leaf(object):
def __init__(self, color='green'):
self.color = color
class ColorChangingLeaf(Leaf):
def change(self, new_color='brown'):
self.color = new_color
class DeciduousLeaf(Leaf):
def fall(self):
print "Plunk!"
class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
pass
在上面的例子中, MapleLeaf
就使用了多重继承,它可以使用两个父类的方法:
leaf = MapleLeaf()
leaf.change("yellow")
print leaf.color
leaf.fall()
如果同时实现了不同的接口,那么,最后使用的方法以继承的顺序为准,放在前面的优先继承:
class Leaf(object):
def __init__(self, color='green'):
self.color = color
class ColorChangingLeaf(Leaf):
def change(self, new_color='brown'):
self.color = new_color
def fall(self):
print "Spalt!"
class DeciduousLeaf(Leaf):
def fall(self):
print "Plunk!"
class MapleLeaf(ColorChangingLeaf, DeciduousLeaf):
pass
leaf = MapleLeaf()
leaf.fall()
class MapleLeaf(DeciduousLeaf, ColorChangingLeaf):
pass
leaf = MapleLeaf()
leaf.fall()
事实上,这个顺序可以通过该类的 __mro__
属性或者 mro()
方法来查看:
MapleLeaf.__mro__
MapleLeaf.mro()
考虑更复杂的例子:
class A(object):
pass
class B(A):
pass
class C(A):
pass
class C1(C):
pass
class B1(B):
pass
class D(B1, C):
pass
调用顺序:
D.mro()